package me.younian.transmitNIO;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.FileNotFoundException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/2.
 */
public class ClientThread implements Runnable {
    private static final Logger logger = Logger.getLogger(ClientThread.class);

    @Override
    public void run() {
        NioSocketConnector connector = new NioSocketConnector();
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();
        chain.addLast("myChin", new ProtocolCodecFilter(
                new ObjectSerializationCodecFactory()));
        ClientHandler clientHandler = new ClientHandler();
        connector.setHandler(clientHandler);
        connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
        ConnectFuture cf = connector.connect(new InetSocketAddress("localhost", 9999));
    }

    private class ClientHandler extends IoHandlerAdapter {
        public void sessionOpened(IoSession session) throws Exception {
            logger.info("sessionOpened");
        }

        public void sessionClosed(IoSession session) {
            logger.info("sessionClosed");
        }

        public void messageReceived(IoSession session, Object message)
                throws Exception {
            Map<String, Object> req = (HashMap) message;

            HttpRequestMessage requestMessage = (HttpRequestMessage) req.get("req");
            logger.info("Request: " + requestMessage.getContext());
            Map<String, Object> result = null;
            try {
                result = HttpRequest.sendGet("http://localhost/" + requestMessage.getContext());
            } catch (FileNotFoundException fileNotFoundException) {
            }
            Map<String, Object> map = new HashMap<>();
            map.put("id", req.get("id"));
            map.put("res", result);
            session.write(map);
        }

        @Override
        public void exceptionCaught(IoSession session, Throwable cause)
                throws Exception {
            super.exceptionCaught(session, cause);
            logger.error(cause.getMessage());
            Thread.sleep(3000);
            run();
        }
    }

}

